import { defineStore } from 'pinia';
import request, { http } from '@/utils/request';
import { ref } from 'vue';
import type {
  BannerList,
  Brand,
  CategoryList,
  GoodsList,
  HomeProduct,
  Special,
  SubCategory,
} from '@/types';
export const useHomeStore = defineStore(
  'home',
  () => {
    const categoryList = ref<CategoryList>([]);
    // 获取分类信息
    const getAllCategory = async () => {
      const res = await request.get('/home/category/head');
      res.data.result.forEach((item) => {
        item.open = false;
      });
      categoryList.value = res.data.result;
    };
    const show = (id: string) => {
      const itemObj = categoryList.value.find((item) => item.id === id);
      itemObj.open = true;
    };
    const hide = (id: string) => {
      const itemObj = categoryList.value.find((item) => item.id === id);
      itemObj.open = false;
    };

    // 获得轮播图数据
    const bannerList = ref<BannerList>([]);
    const getBannerList = async () => {
      const res = await request.get('/home/banner');
      bannerList.value = res.data.result;
    };
    // 获取新鲜好物数据
    const newGoodsList = ref<GoodsList>([]);
    const getNewGoodsList = async () => {
      const res = await request.get('/home/new');
      newGoodsList.value = res.data.result;
    };
    // 获取人气推荐数据
    const hotGoodsList = ref<GoodsList>([]);
    const getHotGoodsList = async () => {
      const res = await request.get('/home/hot');
      // console.log('/home/hot', res);
      hotGoodsList.value = res.data.result;
    };
    // 获取热门品牌数据
    const brandList = ref<Brand[]>([]);
    const getBrandList = async () => {
      const res = await http<Brand[]>('GET', '/home/brand');
      brandList.value = res.data.result;
    };
    // 获得商品区块数据
    const productList = ref<HomeProduct[]>([]);
    const getProductList = async () => {
      const res = await http<HomeProduct[]>('GET', '/home/goods');
      productList.value = res.data.result;
    };
    // 获得最新专辑数据
    const specialList = ref<Special[]>([]);
    const getSpecialList = async () => {
      const res = await http<Special[]>('GET', '/home/special');
      specialList.value = res.data.result;
    };
    // 获得二级类目-筛选
    const subCategory = ref<SubCategory>();
    const getSubFilter = async (id: string) => {
      const res = await http<SubCategory>('get', '/category/sub/filter', {
        id,
      });
      subCategory.value = res.data.result;
    };
    return {
      getAllCategory,
      categoryList,
      show,
      hide,
      getBannerList,
      bannerList,
      getNewGoodsList,
      newGoodsList,
      hotGoodsList,
      getHotGoodsList,
      getBrandList,
      brandList,
      getProductList,
      productList,
      specialList,
      getSpecialList,
      getSubFilter,
      subCategory,
    };
  },
  {
    persist: {
      paths: ['categoryList'],
    },
  }
);
